<template>
	<a-drawer :visible="_d.visible" width="500" title="我要反馈" @close="close()">
    <a-form :label-col="{style: {width: '6em'}}">
    	<a-form-item label="标题" v-bind="validateInfos.title">
    		<a-input v-model:value="_d.form.title" placeholder="请使用一句话描述您的反馈" allowClear></a-input>
    	</a-form-item>
    	<a-form-item label="联系电话" v-bind="validateInfos.tel">
    		<a-input v-model:value="_d.form.tel" placeholder="请输入联系电话" allowClear></a-input>
    	</a-form-item>
    	<a-form-item label="反馈描述" v-bind="validateInfos.content">
    		<a-textarea v-model:value="_d.form.content" placeholder="有体验问题、BUG或功能缺失？请将您的宝贵建议反馈给到我们。" :auto-size="{ minRows: 5, maxRows: 5 }" allowClear></a-textarea>
    	</a-form-item>
    	<a-form-item label="截图标记">
    		<div class="screenshot-box">
    			<a-radio-group v-model:value="_d.choiceType" @change="typeChange">
			      <a-radio v-for="(item, index) in _d.imageTypes" :key="index" :value="item.value">{{item.label}}</a-radio>
			    </a-radio-group>
			    <div class="img-box">
			    	<img v-if="nowImage" :src="nowImage"/>
			    	<div class="img-mark"></div>
			    	<template v-if="_d.choiceType == 1">
			    		<input v-show="false" ref="fileRef" type="file" accept="image/png,image/jpeg" @change="fileChange"/>
			    		<div class="btn-box">
			    			<span class="btn" @click="uploadImage()">上传图片</span>
				    		<span v-if="nowImage" class="btn" @click="doMark()">点击标注内容</span>
			    		</div>
			    	</template>
			    	<template v-else>
			    		<div v-if="!nowImage && !_d.captureError" class="loading"><a-spin class="icon"/>正在处理页面截图</div>
			    		<div v-if="_d.captureError" class="capture-error">自动截屏失败，请<a target="_blank" href="https://www.win7zhijia.cn/win10jc/win10_51272.html">手动截屏</a>并上传图片</div>
			    		<div class="btn-box">
			    			<span v-if="nowImage || _d.captureError" class="btn" @click="doScreenshot()">重新截屏</span>
			    			<span v-if="nowImage" class="btn" @click="doMark()">点击标注内容</span>
			    		</div>
			    	</template>
			    </div>
			    <div class="tip"><info-circle-outlined class="icon" />请注意保护敏感信息，可进行涂抹避免泄露</div>
    		</div>
    	</a-form-item>
    	<div style="color:red;padding-left:6em">提示：建议一经采纳，会有微信红包奖励</div>
    </a-form>
    <template #extra>
      <a-space>
        <a-button @click="close()">取消</a-button>
        <a-button @click="reset()">重置</a-button>
        <a-button :loading="_d.btnLoading" type="primary" @click="submit()">提交</a-button>
      </a-space>
    </template>

    <markModal ref="markModalRef"></markModal>
  </a-drawer>
</template>

<script setup>
	import { reactive, ref, computed } from 'vue'
	import { Form, notification } from 'ant-design-vue';
	import { InfoCircleOutlined } from '@ant-design/icons-vue';
	import markModal from "./markModal.vue";

	import domtoimage from 'dom-to-image';


	const fileRef = ref();
	const markModalRef = ref();
	
	const props = defineProps({
		// 反馈类型
		types: {
			type: Array
		},
		// 字段名称
		fieldNames: {
			type: Object
		},
		tokenKey: {
			type: String
		},
		// 接口
		api: {
			type: String
		},
		// axios实例
		instance: {
			type: Function
		}
	})

	const _d = reactive({
		visible: false,
		btnLoading: false,

		form: {
			title: '',
			tel: '',
			content: '',
		},

		rules: {
			title: [
				{ required: true, trigger: 'change', message: '请输入标题' }
			],
			tel: [
				{required: true, pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, trigger: 'change', message: '请输入正确的联系电话'}
			],
			content: [
				{ required: true, trigger: 'change', message: '请输入反馈描述' }
			]
		},

		// 图片类型
		choiceType: 1,
		imageTypes: [
			{label: '上传图片', value: 1},
			// {label: '当前页截图', value: 2},
		],

		// 是否截屏失败
		captureError: true,
		upImg: '', // 上传图片
		capImg: '', // 截屏图片
	})

	// 当前的图片
	const nowImage = computed({
		get: () => {
			if(_d.choiceType == 1) {
				return _d.upImg;
			} else if (_d.choiceType == 2) {
				return _d.capImg;
			}
		},
		set: value => {
			if(_d.choiceType == 1) {
				_d.upImg = value;
			} else if (_d.choiceType == 2) {
				_d.capImg = value;
			}
		}
	})

	// 验证
	const { clearValidate, resetFields, validate, validateInfos } = Form.useForm(_d.form, _d.rules);

	function open () {
		_d.captureError = false;

		_d.visible = true;
	}

	// 图片类型改变
	function typeChange() {
		if(_d.choiceType == 2 && !_d.capImg) {
			doScreenshot();
		} 
	}

	// 上传图片
	function uploadImage() {
		fileRef.value.click();
	}

	// 文件改变
	function fileChange() {
		let oFile = fileRef.value;
		let files = oFile.files;
    if (!files.length) {
      return;
    }
    let file = files[0];
    oFile.value = '';

    // 图片验证
    let arr = file.name.split('.');
    let suffix = arr[arr.length - 1].toLowerCase();
    if(['png', 'jpg', 'jpeg'].indexOf(suffix) == -1) {
    	notification.error({
    		message: '提示',
    		description: "图片格式仅支持jpg\\jpeg\\png"
    	})
    	return;
    }

    // 大小验证
    if(file.size > 50*1024*1024) {
    	notification.error({
    		message: '提示',
    		description: "请选择小于50M的图片上传"
    	})
    	return;
    }

    // 将图片文件转换为base64
    getBase64(file, base64Url => {
    	// 设置上传的图片
    	_d.upImg = base64Url;
    })
	}

	function getBase64(img, callback) {
	  const reader = new FileReader();
	  reader.readAsDataURL(img);
	  reader.addEventListener('load', () => callback(reader.result));
	}

	// 点击标注
	function doMark() {
		markModalRef.value.open(nowImage.value, image => {
			nowImage.value = image;
		});
	}

	// 截屏
	function doScreenshot() {
		_d.captureError = false;

		_d.capImg = '';
		var node = document.getElementById('app');
		domtoimage.toPng(node).then(dataUrl => {
			_d.capImg = dataUrl;
		}).catch(() => {
			_d.captureError = true;
		})
	}

	// 提交
	function submit() {
		validate().then(() => {
			let data = {
				..._d.form,
			}
			data.image = nowImage.value;
			_d.btnLoading = true;
			props.instance({
				method: 'POST',
				url: '/Feedback/insertfeedback',
				data: data
			}).then(res => {
				if(res.status != 200) {
					notification.error({
		    		message: '提示',
		        description: '反馈失败'
		    	})
					return;
				}
				notification.success({
	    		message: '提示',
	        description: '反馈成功'
	    	})
			}).finally(() => {
				_d.btnLoading = false;
			})
		})
	}

	// 重置
	function reset() {
		resetFields();
		_d.choiceType = 1;
		_d.upImg = '';
		_d.capImg = '';
	}

	// 关闭
	function close() {
		clearValidate();
		_d.visible = false;
	}

	defineExpose({
		open
	})

</script>
<style lang="less" scoped>
.screenshot-box {
	padding-top: 6px;
	.img-box {
		position: relative;
		height: 180px;
		margin-top: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
		.img-mark {
			position: absolute;
			z-index: 1;
	    top: 0;
	    bottom: 0;
	    left: 0;
	    right: 0;
	    background-color: rgba(0,0,0,.3);
		}
		.btn-box {
			position: absolute;
			z-index: 2;
			top: 50%;
			left: 0;
			right: 0;
			margin-top: -17px;
			display: flex;
	    align-items: center;
	    justify-content: center;
	    gap: 10px;
			.btn {
		    width: 100px;
		    height: 34px;
		    line-height: 32px;
		    text-align: center;
		    color: #fff;
		    font-size: 14px;
		    border: 1px solid #fff;
	    	box-sizing: border-box;
	    	cursor: pointer;
	    }
		}
		.loading {
			height: 40px;
			line-height: 40px;
			color: #333;
			text-align: center;
			.icon {
				margin-right: 10px;
			}
		}
		.capture-error {
			position: absolute;
			z-index: 4;
			top: 50%;
			left: 0;
			right: 0;
			margin-top: -55px;
			line-height: 30px;
			text-align: center;
			a {
				margin: 0 4px;
			}
		}
		img {
			max-width: 100%;
			max-height: 100%;
		}
	}
	.tip {
		margin-top: 5px;
		color: #979797;
		font-size: 12px;
		.icon {
			margin-right: 5px;
		}
	}
}
</style>